package com.example.doufacedemo;

import android.app.Activity;
import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.view.Surface;

import androidx.annotation.Nullable;

import com.jiangdg.usbcamera.UVCCameraHelper;
import com.serenegiant.usb.widget.CameraViewInterface;
import com.serenegiant.usb.widget.UVCCameraTextureView;

public class UvcActivity extends Activity {
    private CameraViewInterface mUVCCameraView;
    private UVCCameraHelper mCameraHelper;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_uvc);

        init();
    }

    private void init() {
        mUVCCameraView = findViewById(R.id.tv_surface);

        mUVCCameraView.setCallback(mCallback);
        mCameraHelper = UVCCameraHelper.getInstance();
// set default preview size
        mCameraHelper.setDefaultPreviewSize(480, 470);
// set default frame format，defalut is UVCCameraHelper.Frame_FORMAT_MPEG
// if using mpeg can not record mp4,please try yuv
// mCameraHelper.setDefaultFrameFormat(UVCCameraHelper.FRAME_FORMAT_YUYV);
        mCameraHelper.initUSBMonitor(this, mUVCCameraView, listener);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    private CameraViewInterface.Callback mCallback = new CameraViewInterface.Callback() {

        @Override
        public void onSurfaceCreated(CameraViewInterface view, Surface surface) {
            if (mCameraHelper.isCameraOpened()) {
                mCameraHelper.startPreview(mUVCCameraView);

            }
        }

        @Override
        public void onSurfaceChanged(CameraViewInterface view, Surface surface, int width, int height) {

        }

        @Override
        public void onSurfaceDestroy(CameraViewInterface view, Surface surface) {
            if (mCameraHelper.isCameraOpened()) {
                mCameraHelper.stopPreview();

            }
        }
    };

    private UVCCameraHelper.OnMyDevConnectListener listener = new UVCCameraHelper.OnMyDevConnectListener() {

        @Override
        public void onAttachDev(UsbDevice device) {
            // request open permission(must have)

            if (mCameraHelper != null) {
                mCameraHelper.requestPermission(0);
            }

        }

        @Override
        public void onDettachDev(UsbDevice device) {
            // close camera(must have)

            mCameraHelper.closeCamera();

        }

        @Override
        public void onConnectDev(UsbDevice device, boolean isConnected) {

        }

        @Override
        public void onDisConnectDev(UsbDevice device) {

        }
    };
}
